package com.xuedongzhilian.controller;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.entity.Rank;
import com.xuedongzhilian.service.IRankService;
import com.xuedongzhilian.service.IRankingService;
import com.xuedongzhilian.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 段位体系控制器
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/rank")
public class RankController {

    @Resource
    private IRankService rankService;
    
    @Resource
    private IRankingService rankingService;

    /**
     * 获取当前用户段位信息
     */
    @GetMapping("/me")
    public Result getUserRank() {
        Long userId = UserHolder.getUser().getId();
        Rank rank = rankService.lambdaQuery()
                .eq(Rank::getUserId, userId)
                .one();
        return Result.ok(rank);
    }

    /**
     * 获取段位排行榜
     */
    @GetMapping("/ranking")
    public Result getRankRanking() {
        return rankingService.getRankRanking();
    }

    /**
     * 更新用户段位信息（测试用）
     */
    @PostMapping("/update")
    public Result updateRank(@RequestBody Rank rank) {
        Long userId = UserHolder.getUser().getId();
        Rank existingRank = rankService.lambdaQuery()
                .eq(Rank::getUserId, userId)
                .one();
                
        if (existingRank != null) {
            rank.setId(existingRank.getId());
            rank.setUserId(userId);
            boolean success = rankService.updateById(rank);
            if (success) {
                return Result.ok(rank);
            } else {
                return Result.fail("更新失败");
            }
        } else {
            rank.setUserId(userId);
            boolean success = rankService.save(rank);
            if (success) {
                return Result.ok(rank);
            } else {
                return Result.fail("创建失败");
            }
        }
    }
}